<template>
  <a-card
    class="edgeListPage"
    :bordered="false"
    :bodyStyle="{ minHeight: `${layoutContentHeight - pageHeaderHeight}px` }"
  >
    <div class="edge-header">
      <a-form layout="inline">
        <a-form-item :label="$t('common.name')">
          <a-input v-model.trim="queryParams.name" allowClear />
        </a-form-item>
        <a-form-item :label="$t('common.status')">
          <a-select style="width:200px" v-model="queryParams.state" placeholder="请选择">
            <a-select-option value="">{{ $t('common.all') }}</a-select-option>
            <a-select-option :value="0">{{ $t('common.offline') }}</a-select-option>
            <a-select-option :value="1">{{ $t('common.online') }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" icon="search" @click="onSearch">{{ $t('common.query') }}</a-button>
          <a-button icon="reload" style="margin-left:8px" @click="resetQuery">{{ $t('common.reset') }}</a-button>
          <a-button v-action:add type="primary" style="margin-left:8px" icon="plus" @click="handleCreate">{{
            $t('button.add')
          }}</a-button>
        </a-form-item>
      </a-form>
    </div>
    <a-spin :spinning="spinning">
      <div v-if="list.length" class="edge-content">
        <div class="edge-content-list">
          <a-row :gutter="16" type="flex" justify="start" v-for="i in Math.ceil(list.length / 6)" :key="i">
            <template v-for="(item, index) in list">
              <a-col :span="4" :key="item.id" v-if="index >= (i - 1) * 6 && index < i * 6">
                <div class="edge-content-list-item">
                  <div class="big-dot">
                    <div>
                      <a-badge :status="item.state === 1 ? 'success' : 'error'" />{{ $t(stateMap[item.state]) }}
                    </div>
                    <div class="big-dot-ellipsis" v-action:edit|delete>
                      <a-dropdown :trigger="['hover']">
                        <a href="javascript:;">
                          <a-icon type="ellipsis" />
                        </a>
                        <a-menu slot="overlay" @click="({ key }) => onDropdownMenuClick(key, item)">
                          <a-menu-item key="edit" v-action:edit>
                            <a-icon type="edit" />
                            {{ $t('common.edit') }}
                          </a-menu-item>
                          <a-menu-item key="delete" v-action:delete>
                            <a-icon type="delete" />
                            {{ $t('common.delete') }}
                          </a-menu-item>
                        </a-menu>
                      </a-dropdown>
                    </div>
                  </div>
                  <div class="edge-content-list-item-middle">
                    <div class="edge-content-list-item-middle-img">
                      <img slot="cover" alt="example" src="@/assets/images/edge/edge.png" />
                    </div>
                    <div class="edge-content-list-item-middle-indicator">
                      <div class="edge-content-list-item-middle-indicator-item">
                        <div>cpu:</div>
                        <a-progress
                          :percent="item.cpuUsage"
                          size="small"
                          status="active"
                          :strokeColor="item.cpuUsage > 70 ? '#f5222d' : item.cpuUsage > 30 ? '' : '#52c41a'"
                        />
                      </div>
                      <div class="edge-content-list-item-middle-indicator-item">
                        <div>内存:</div>
                        <a-progress
                          :percent="item.memoryUsage"
                          size="small"
                          status="active"
                          :strokeColor="item.memoryUsage > 80 ? '#f5222d' : item.memoryUsage > 50 ? '' : '#52c41a'"
                        />
                      </div>
                      <div class="edge-content-list-item-middle-indicator-item">
                        <div>磁盘:</div>
                        <a-progress
                          :percent="item.diskUsage"
                          size="small"
                          status="active"
                          :strokeColor="item.diskUsage > 80 ? '#f5222d' : item.diskUsage > 40 ? '' : '#52c41a'"
                        />
                      </div>
                    </div>
                  </div>
                  <div class="edge-content-list-item-info">
                    <div class="edge-content-list-item-info-name" :title="item.name">
                      {{ item.name }}
                    </div>
                    <div class="edge-content-list-item-info-description" :title="item.description">
                      {{ item.description }}
                    </div>
                    <div class="edge-content-list-item-info-bottom">
                      <div class="edge-content-list-item-info-bottom-num" :title="item.number">
                        {{ item.number }}
                      </div>
                      <div class="edge-content-list-item-info-bottom-heartbeatUrl" :title="item.heartbeatUrl">
                        <a @click="goTo(item)">{{ item.heartbeatUrl }}</a>
                      </div>
                    </div>
                  </div>
                </div>
              </a-col>
            </template>
          </a-row>
        </div>
        <div style="float:right">
          <a-pagination
            v-if="list.length"
            show-quick-jumper
            :show-total="total => $t('common.total', { name: total })"
            v-model="pageParams.pageNo"
            :defaultPageSize="12"
            :total="total"
            @change="onChange"
          />
        </div>
      </div>
      <a-empty v-else />
    </a-spin>
    <edge-form ref="edgeForm" @ok="onCallback" />
  </a-card>
</template>
<script>
import { layoutMixin } from '@/utils/mixin'
import {
  getEdgemanagementPageList,
  deleteEdgemanagement,
  getEdgemanagementEdgeToken
} from '@/api/edgeManagement/EdgeManagementController'
import EdgeForm from './modules/EdgeForm'
import websocket from '@/utils/websocket'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { parseUri, getQueryParams } from '@/utils/util'
import Vue from 'vue'
let ws = null

const initialqueryParams = {
  name: '',
  state: ''
}
const pageParams = {
  pageNo: 1,
  pageSize: 12
}
const stateMap = {
  null: 'common.offline',
  0: 'common.offline',
  1: 'common.online'
}
export default {
  name: 'EdgeList',
  mixins: [layoutMixin],
  components: {
    EdgeForm
  },
  data () {
    return {
      spinning: true,
      initFlag: true,
      pageParams: { ...pageParams },
      total: 0,
      queryParams: { ...initialqueryParams },
      list: [],
      stateMap,
      token: ''
    }
  },
  created () {
    const { pageNo, pageSize, name, state } = this.$route.query
    this.pageParams = {
      pageNo: pageNo ? parseInt(pageNo) : 1,
      pageSize: pageSize ? parseInt(pageSize) : 12
    }
    this.queryParams = {
      name,
      state: state || ''
    }
    this.token = Vue.ls.get(ACCESS_TOKEN)
    this.getEdgemanagementPageList()
    this.initWs()
  },
  beforeDestroy () {
    ws && ws.close()
  },
  methods: {
    onSearch () {
      this.getEdgemanagementPageList()
    },
    resetQuery () {
      this.pageParams = { ...pageParams }
      this.queryParams = { ...initialqueryParams }
      this.getEdgemanagementPageList()
    },
    // 新建应用
    handleCreate () {
      this.$refs.edgeForm.add()
    },
    getEdgemanagementPageList (params) {
      this.spinning = true
      const pageParams = this.initFlag ? { ...params, ...this.pageParams } : { ...this.pageParams, ...params }
      getEdgemanagementPageList({
        ...this.queryParams,
        ...pageParams
      })
        .then(res => {
          this.$router.push({
            ...this.$route,
            query: {
              ...pageParams,
              ...getQueryParams(this.queryParams)
            }
          })
          this.initFlag = false
          this.total = res.data.totalCount
          this.list = res.data.data
        })
        .finally(() => {
          this.spinning = false
        })
    },
    async onChange (pageNo) {
      const params = { ...this.pageParams }
      params.pageNo = pageNo
      this.data = await this.getEdgemanagementPageList(params)
    },

    onDropdownMenuClick (key, record) {
      if (key === 'edit') {
        this.$refs.edgeForm.edit(record)
      } else if (key === 'delete') {
        this.$confirm({
          title: this.$t('common.warning'),
          content: this.$t('message.warning.delete', {
            name: record.name
          }),
          onOk: () => {
            deleteEdgemanagement({ ids: record.id }).then(res => {
              this.$message.success('操作成功')
              this.onSearch()
            })
          }
        })
      } else return
    },
    // 批量删除
    onBatchDel (ids) {
      this.$confirm({
        title: this.$t('common.warning'),
        content: this.$t('message.warning.batchDel', {
          name: 'edge'
        }),
        onOk: () => {
          deleteEdgemanagement({ ids: ids.join(',') }).then(res => {
            this.$message.success('操作成功')
            this.onSearch()
          })
        }
      })
    },
    onCallback (type) {
      if (type === 'add') {
        this.pageParams = { ...pageParams }
      }
      this.onSearch()
    },
    goTo (record) {
      getEdgemanagementEdgeToken({ id: record.id }).then(res => {
        if (res.data && res.data['Access-Token']) {
          const option = parseUri(record.heartbeatUrl)
          const url = `${option.protocol}${option.protocol ? '://' : ''}${option.host}?token=${
            res.data['Access-Token']
          }`
          window.open(url)
        }
      })
    },
    initWs () {
      if (!this.token) return
      ws = websocket(
        {
          onmessage: e => {
            if (e.data) {
              if (e.data) {
                try {
                  const data = JSON.parse(e.data)
                  data.forEach(item => {
                    for (const d of this.list) {
                      if (item.id === d.id) {
                        d.state = item.state
                        d.cpuUsage = item.cpuUsage || 0
                        d.diskUsage = item.diskUsage || 0
                        d.memoryUsage = item.memoryUsage || 0
                        break
                      }
                    }
                  })
                } catch (error) {}
              }
            }
          }
        },
        { url: `/ws/?appType=edge&Access-Token=${this.token}` }
      )
    }
  }
}
</script>
<style lang="less" scoped>
.edgeListPage {
  /deep/ .ant-card-body {
    padding: 12px 24px;
    overflow-x: auto;
  }
  .edge-header {
  }
  .edge-content {
    min-width: 800px;
    margin: 20px 0;
    &-list {
      &-item {
        margin-bottom: 20px;
        border: 1px solid #e8e8e8;
        .big-dot {
          display: flex;
          justify-content: space-between;
          padding: 6px 8px 0 8px;
          .anticon-ellipsis {
            font-size: 20px;
          }
        }
        .big-dot /deep/.ant-badge-status-dot {
          width: 12px;
          height: 12px;
          box-shadow: 0 0 4px;
          border: 1px solid #fff;
        }
        &-middle {
          margin: 12px 0;
          padding-left: 12px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          &-img {
            width: 30%;
            img {
              width: 100%;
            }
          }
          &-indicator {
            width: 70%;
            padding: 0px 30px 0 10px;
            &-item {
              font-size: 12px;
            }
          }
        }

        &-info {
          padding: 0 12px 12px 12px;
          color: rgba(0, 0, 0, 0.85);
          &-name,
          &-description {
            overflow: hidden;
            height: 24px;
            font-size: 14px;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
          &-description {
            font-size: 12px;
            color: rgba(0, 0, 0, 0.45);
          }
          &-bottom {
            margin-top: 8px;
            font-size: 12px;
            color: rgba(0, 0, 0, 0.45);
            display: flex;
            justify-content: space-between;
            &-num,
            &-heartbeatUrl {
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
            }
            &-num {
              width: 60px;
            }
            &-heartbeatUrl {
              width: calc(~'100% - 60px');
              text-align: right;
            }
          }
        }
      }
    }
  }
}
</style>
